from fastapi import APIRouter, Request, HTTPException
from typing import Dict, Any
import logging
from app.models.translate_request import TranslateRequest
from app.services.translate_service import translation_service
from app.utils.error_handling import (
    BadRequestError,
    NotFoundError,
    InternalServerError,
    ErrorHandler
)

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 创建路由器
router = APIRouter(prefix="/api/v1", tags=["翻译"])

@router.post("/translate")
async def translate(request: Request, req_data: TranslateRequest) -> Dict[str, Any]:
    """
    翻译接口
    提供文本翻译服务，支持多语言互译，并集成积分扣减和日志记录功能
    """
    try:
        client_ip = request.client.host
        logging.info(f"请求来自 {client_ip}, 店铺: {req_data.shopify_domain}, 目标语言: {req_data.target_language}")
        
        # 调用翻译服务执行完整的翻译流程
        # 服务层会处理：积分检查、翻译执行、积分扣减、日志记录等所有业务逻辑
        result = translation_service.perform_translation(
            shop_domain=req_data.shopify_domain,
            source_text=req_data.text,
            target_language=req_data.target_language,
            source_language=req_data.source_language,
            metadata_model=req_data.metadata_model
        )
        
        # 记录响应日志
        logging.info(f"翻译请求处理完成 - 状态: {'成功' if result.get('is_success') == 1 else '失败'}, 日志ID: {result.get('data', {}).get('log_id')}")
        
        return result
        
    except ValueError as e:
        # 处理验证错误
        logging.error(f"请求参数验证失败: {str(e)}")
        error = BadRequestError(f"Parameter validation failed: {str(e)}")
        return ErrorHandler.handle_api_error(
            error,
            shopify_domain=req_data.shopify_domain or "",
            metadata_model=req_data.metadata_model or ""
        )
    except Exception as e:
        # 处理未预期的错误
        import traceback
        logging.error(f"处理请求出错: {e}")
        logging.error(f"错误堆栈: {traceback.format_exc()}")
        logging.error(f"请求参数: shopify_domain={req_data.shopify_domain}, text={req_data.text[:100]}..., target_language={req_data.target_language}")
        return ErrorHandler.handle_generic_exception(
            e,
            shopify_domain=req_data.shopify_domain or "",
            metadata_model=req_data.metadata_model or ""
        )

@router.get("/translate/history/{shopify_domain}")
async def get_translation_history(shopify_domain: str, limit: int = 50, offset: int = 0) -> Dict[str, Any]:
    """
    获取翻译历史记录
    """
    # 参数验证
    if not shopify_domain or len(shopify_domain) < 3:
        error = BadRequestError("Invalid shop domain")
        return ErrorHandler.handle_api_error(error, shopify_domain)
    
    try:
        # 调用服务层获取历史记录
        history = translation_service.get_translation_history(shopify_domain, limit, offset)
        
        # 统一响应格式
        return {
            "is_success": 1,
            "message": "Translation history retrieved successfully",
            "shopify_domain": shopify_domain,
            "data": {
                "history": history,
                "limit": limit,
                "offset": offset
            }
        }
    except Exception as e:
        logging.error(f"获取翻译历史失败: {str(e)}")
        return ErrorHandler.handle_generic_exception(e, shopify_domain)


@router.get("/translate/points/history/{shopify_domain}")
async def get_translation_points_history(shopify_domain: str, limit: int = 50, offset: int = 0) -> Dict[str, Any]:
    """
    获取翻译积分交易历史
    """
    try:
        # 参数验证
        if not shopify_domain or len(shopify_domain) < 3:
            error = BadRequestError("Invalid shop domain")
            return ErrorHandler.handle_api_error(error, shopify_domain)
        
        # 从模型直接获取翻译积分交易历史
        from app.models.translation_point_transaction import translation_point_transaction_model
        history = translation_point_transaction_model.get_shop_transaction_history(
            shop_domain=shopify_domain,
            limit=limit,
            offset=offset
        )
        
        # 统一响应格式
        return {
            "is_success": 1,
            "message": "Translation points history retrieved successfully",
            "shopify_domain": shopify_domain,
            "data": {
                "history": history,
                "limit": limit,
                "offset": offset
            }
        }
    except Exception as e:
        logging.error(f"获取翻译积分交易历史失败: {str(e)}")
        return ErrorHandler.handle_generic_exception(e, shopify_domain)


@router.get("/translate/log/{log_id}")
async def get_translation_log(log_id: str) -> Dict[str, Any]:
    """
    获取翻译日志详情
    """
    try:
        # 参数验证
        if not log_id or len(log_id) != 36:
            error = BadRequestError("Invalid log ID")
            return ErrorHandler.handle_api_error(error, "")
        
        # 调用服务层获取日志详情
        log_detail = translation_service.get_translation_log(log_id)
        
        if not log_detail:
            error = NotFoundError("Translation log not found")
            return ErrorHandler.handle_api_error(error, "")
        
        # 统一响应格式
        return {
            "is_success": 1,
            "message": "Translation log retrieved successfully",
            "shopify_domain": log_detail.get("shop_domain", ""),
            "data": log_detail
        }
        
    except Exception as e:
        logging.error(f"获取翻译日志详情失败: {str(e)}")
        return ErrorHandler.handle_generic_exception(e, "")